package com.chenyun.store.aws;

import cn.hutool.core.io.FileUtil;
import com.chenyun.store.pojo.StoreDTO;
import org.apache.commons.io.FileUtils;

import java.io.*;

/**
 * 本地上传
 *
 * @author: Lonni
 * @date: 2023/11/6 0006 11:31
 */
public class OssLocalClientService implements IOssClientService {


    private final StoreDTO configDTO;

    public OssLocalClientService(StoreDTO configDTO) {
        this.configDTO = configDTO;
    }


    /**
     * 上传文件
     *
     * @param data
     * @param path
     * @param contentType
     * @return
     */
    @Override
    public String upload(byte[] data, String path, String contentType) throws IOException {
        String savePath = getSavePath(configDTO, path);
        FileUtils.writeByteArrayToFile(new File(savePath), data);
        return getUrl(configDTO, savePath);
    }

    @Override
    public String upload(InputStream inputStream, String path, String contentType) throws IOException {

        FileOutputStream outputStream = null;
        try {
            String savePath = getSavePath(configDTO, path);
            File file = new File(savePath);
            outputStream = new FileOutputStream(file);
            int bytesRead;
            byte[] buffer = new byte[1024];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return getUrl(configDTO, savePath);
        } finally {
            outputStream.close();
            inputStream.close();
        }
    }

    @Override
    public InputStream getObjectContent(String path) throws FileNotFoundException {

        FileInputStream inputStream = new FileInputStream(new File(getSavePath(configDTO, path)));
        return inputStream;
    }

    @Override
    public String upload(File file, String path) {
        String savePath = getSavePath(configDTO, path);
        File file1 = FileUtil.copyFile(file, new File(savePath));
        return getUrl(configDTO, getSavePath(configDTO, savePath));
    }

    @Override
    public void delete(String path) {
        FileUtil.del(new File(getSavePath(configDTO, path)));
    }
}



